//
//  YFPersonDataVC.m
//  SquashSpark
//
//  Created by Coollang on 2017/11/15.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFPersonDataVC.h"
#import "YFPersonDataCell.h"
#import "User.h"
#import "YFPersonModel.h"
#import "YFAlertHelper.h"
#import "YFAlternativeView.h"
#import "YFHeightPickerView.h"
#import "YFWeightAlertPickerView.h"
#import "YFTrainingAlertPickerView.h"
#import "Common.h"
#import "UIView+Frame.h"
#import "NSString+Extension.h"
#import <YYKit/YYKit.h>
#import "YFRacquetController.h"
#import "PhotoActionSheetViewController.h"
#import "SystemSelectPhotoManager.h"
#import "YFLoginHelper.h"
#import <SDWebImage/UIImageView+WebCache.h>

@interface YFPersonDataVC ()<UITabBarDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tabelView;
/** 头像图片 */
@property (nonatomic, strong) UIImageView *headImageView;
/** nextBtn */
@property (nonatomic, strong) UIButton *nextButton;

/** 本地老的用户信息 */
@property (nonatomic, strong) UserInfoItem *oldUserInfoItem;

// 是否设置了左右手
@property (nonatomic, assign) BOOL setedHandType;
/** 是否设置了身高 */
@property (nonatomic, assign)BOOL setedHeight;
/** 是否设置了体重 */
@property (nonatomic, assign)BOOL setedWeight;
/** 是否设置了训练时间 */
@property (nonatomic, assign) BOOL settedTraiing;

@property (nonatomic, strong) SystemSelectPhotoManager *photoManger;

/** 保存按钮 */
@property (nonatomic, strong) UIBarButtonItem *saveItem;

@end

@implementation YFPersonDataVC

- (void)loadView {
    self.tabelView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
    self.tabelView.backgroundColor = kSeparationLineColor;
    self.tabelView.separatorStyle = UITableViewCellSelectionStyleNone;
    self.view = self.tabelView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.oldUserInfoItem = [User getUseInfo];
    self.title = @"Personal Data";
    if (self.isWecomePersonVc == NO) {
        if (self.cacheUserInfoItem == nil) {
            self.cacheUserInfoItem = [[UserInfoItem alloc] init];
            [[User getUseInfo] copyValuesTo:self.cacheUserInfoItem];
        }
        self.saveItem = [[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStyleDone target:self action:@selector(saveBarButtonClick:)];
        self.navigationItem.rightBarButtonItem = self.saveItem;
        self.saveItem.enabled = NO;
    }
    [self configuerTabelView];
    if (self.cacheUserInfoItem) {
        [self.cacheUserInfoItem addObserver:self forKeyPath:@"icon" options:NSKeyValueObservingOptionNew context:nil];
    }
}

- (void)saveBarButtonClick:(UIBarButtonItem *)sender {
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [YFLoginHelper uploadUserInfoWithInfoItem:_cacheUserInfoItem completed:^(NSError *error) {
        if (error == nil) {
            [self.navigationController popViewControllerAnimated:YES];
            [MBProgressHUD showSuccessHudInView:[UIApplication sharedApplication].keyWindow message:@"Saved successfully" afterDelay:1.5];
        }else {
            [MBProgressHUD showFailHudInView:[UIApplication sharedApplication].keyWindow message:error.domain afterDelay:1.5];
        }
    }];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.headImageView sd_setImageWithURL:[NSURL URLWithString:_cacheUserInfoItem.icon] placeholderImage:kUserHeadPlaceholdImage options:SDWebImageLowPriority|SDWebImageRetryFailed];
}

- (void)configuerTabelView {
    [self.tabelView registerNib:[UINib nibWithNibName:@"YFPersonDataCell" bundle:nil] forCellReuseIdentifier:@"YFPersonDataCell"];
    self.tabelView.delegate = self;
    self.tabelView.dataSource = self;
    [self.groups addObject:[self loadTextfieldDataItemSource]];
    [self.groups addObject:[self loadAlertDataItemSource]];
    
    self.tabelView.tableHeaderView = [self creatTabelviewHeaderView];
    self.tabelView.tableFooterView = [self creatTableViewFooterView];
}

#pragma mark - 加载数据源
- (UserGroup *)loadTextfieldDataItemSource {
    UserGroup *textFieldGroup = [[UserGroup alloc] init];
    
    YFPersonModel *itemT0 = [YFPersonModel personModel:@"First Name" subString:_cacheUserInfoItem.FirstName keyBoardType:UIKeyboardTypeDefault];
    itemT0.cellType = kPersonDataCellTextField;
    
    YFPersonModel *itemT1 = [YFPersonModel personModel:@"Last Name" subString:_cacheUserInfoItem.lastName keyBoardType:UIKeyboardTypeDefault];
    itemT1.cellType = kPersonDataCellTextField;
    
    YFPersonModel *itemT2 = [YFPersonModel personModel:@"Age" subString:@(_cacheUserInfoItem.getAge).stringValue keyBoardType:UIKeyboardTypeNumberPad];
    itemT2.cellType = kPersonDataCellTextField;
    itemT2.textFieldMaxLength = 3;
    itemT2.regExpCheck = @"^(?:[1-9]?\\d|100)$";
    
    YFPersonModel *itemT3 = [YFPersonModel personModel:@"City,State/ Province" subString:_cacheUserInfoItem.address keyBoardType:UIKeyboardTypeDefault];
    itemT3.cellType = kPersonDataCellTextField;
    
    YFPersonModel *itemT4 = [YFPersonModel personModel:@"E-mail" subString:_cacheUserInfoItem.email keyBoardType:UIKeyboardTypeEmailAddress];
    itemT4.cellType = kPersonDataCellTextField;
    if (self.isWecomePersonVc == NO && _oldUserInfoItem.loginType == LoginTypeFacebook) {
         [textFieldGroup.items addObjectsFromArray:@[itemT0,itemT1,itemT2,itemT3,itemT4]];
    }else {
         [textFieldGroup.items addObjectsFromArray:@[itemT0,itemT1,itemT2,itemT3]];
    }
   
    return textFieldGroup;
}
- (UserGroup *)loadAlertDataItemSource {
    UserGroup *alertGroup = [[UserGroup alloc] init];
     NSString *genderStr = [SquashEnum stringWithGender:_cacheUserInfoItem.gender];

    YFPersonModel *itemA0 = [YFPersonModel itemWithTitle:@"Gender" andSubTitle:genderStr];
    itemA0.cellType = kPersonDataCellAlert;
    
    __weak typeof(self) weakSelf = self;
    [itemA0 setBlock:^(UserItem *itemT,NSIndexPath *indexPath) {
        kAlternativeSelect currentSelect = _cacheUserInfoItem.gender == GenderUnknown ? kUnselect:(_cacheUserInfoItem.gender == GenderFemale ? kSelectFirst:kSelectSecond);
        [weakSelf setGenderWithPersonModel:(YFPersonModel *)itemT withIndexPath:indexPath defaultValue:currentSelect];
    }];
    
    NSString *heightStr = @"";
    if ([YFUserDefaults generalMetricSystemUnit]) {
         // 使用公制单位
        heightStr = [NSString stringWithFormat:@"%.0fcm",(_cacheUserInfoItem.height.floatValue * 100)];
    }else {
         // 使用英制单位
        NSString *ftinchHeight = [NSString stringWithFormat:@"%zd'%.0f''",[_cacheUserInfoItem ftFormHeight],[_cacheUserInfoItem inchFormHeight]];
        heightStr = ftinchHeight;
    }
    YFPersonModel *itemA1 = [YFPersonModel itemWithTitle:@"Height" andSubTitle:heightStr];
    itemA1.cellType = kPersonDataCellAlert;
    [itemA1 setBlock:^(UserItem *itemT, NSIndexPath *indexpath) {
        [weakSelf setHeightWithPersonmodel:(YFPersonModel *)itemT withIndexPath:indexpath];
    }];
    
    NSString *weightStr = @"";
   
    if ([YFUserDefaults generalMetricSystemUnit]) {
        // 使用公制单位
        weightStr = [NSString stringWithFormat:@"%0.fkg",round([_cacheUserInfoItem.weight floatValue])];
    }else {
        // 使用英制单位
        weightStr = [NSString stringWithFormat:@"%0.flbs",[Common kgToLbs:[_cacheUserInfoItem.weight floatValue]]];
    }
    
    YFPersonModel *itemA2 = [YFPersonModel itemWithTitle:@"Weight" andSubTitle:weightStr];
    itemA2.cellType = kPersonDataCellAlert;
    [itemA2 setBlock:^(UserItem *itemT, NSIndexPath *indexpath) {
        [weakSelf setWeightWithPersonmodel:(YFPersonModel *)itemT withIndexPath:indexpath];
    }];
    
    NSString *handTypeStr = _cacheUserInfoItem.handBallType == HandDirectionTypeBackward ? @"Left":@"Right";
    YFPersonModel *itemA3 = [YFPersonModel itemWithTitle:@"Dominant Hand" andSubTitle:handTypeStr];
    itemA3.cellType = kPersonDataCellAlert;
    [itemA3 setBlock:^(UserItem *itemT,NSIndexPath *indexPath) {
        kAlternativeSelect currentSelect = _cacheUserInfoItem.handBallType == HandDirectionTypeForeward ? kSelectFirst:kSelectSecond;
        [weakSelf setGenderWithPersonModel:(YFPersonModel *)itemT withIndexPath:indexPath defaultValue:currentSelect];
    }];
    
    NSArray *trainStrArr = [self.cacheUserInfoItem.trainingTarget componentsSeparatedByString:@"-"];
    NSString *timeSection = @"";
    NSString *hours = @"";
    if (trainStrArr.count == 2) {
        hours = [NSString stringWithFormat:@"%@hour",trainStrArr.lastObject];
        timeSection = [SquashEnum stringWithTimeSectionType:[trainStrArr.firstObject integerValue]];
    }
    YFPersonModel *itemA4 = [YFPersonModel itemWithTitle:@"Training" andSubTitle:[NSString stringWithFormat:@"%@ %@",hours,timeSection]];
    itemA4.cellType = kPersonDataCellAlert;
    [itemA4 setBlock:^(UserItem *itemT, NSIndexPath *indexpath) {
        [weakSelf setTraingWithPersonmodel:(YFPersonModel *)itemT withIndexPath:indexpath];
    }];
    
    YFPersonModel *itemA5 = [YFPersonModel itemWithTitle:@"E-mail" andSubTitle:_cacheUserInfoItem.email];
    itemA5.cellType = kPersonDataCellAlert;
    if (self.isWecomePersonVc == NO && _oldUserInfoItem.loginType == LoginTypeEmail) {
         [alertGroup.items addObjectsFromArray:@[itemA5,itemA0,itemA1,itemA2,itemA3,itemA4]];
    }else {
         [alertGroup.items addObjectsFromArray:@[itemA0,itemA1,itemA2,itemA3,itemA4]];
    }
    return alertGroup;
}

// 设置性别或左右手
- (void)setGenderWithPersonModel:(YFPersonModel *)model withIndexPath:(NSIndexPath *)indexPath defaultValue:(kAlternativeSelect)select {
    
    BOOL isGender = [model.title isEqualToString:@"Gender"];
    
    AlternativeItem *femaleItem = [AlternativeItem AlternativeItemWithSelectText:isGender ? @"Female":@"Right"];
    
    AlternativeItem *maleItem = [AlternativeItem AlternativeItemWithSelectText:isGender ? @"Male":@"Left"];
    
    YFAlternativeView *genderAllertView = [YFAlternativeView alternativeViewWithTitle:model.title first:femaleItem second:maleItem currentValue:select];
    
    zhPopupController *zhVc = [YFAlertHelper zhpresentEaseInOutAlertView:genderAllertView allowPan:NO dismissTouchMask:YES];
    zhVc.popupView.bounds = CGRectMake(0, 0, 280, 227);
    [genderAllertView setConfirmButtonBlock:^(kAlternativeSelect currntSelect,AlternativeItem *selectItem) {
        if (selectItem != nil) {
            model.subTitle = selectItem.unSelectText;
        }
        if (currntSelect != kUnselect) {
            if(isGender){
                _setedHandType = YES;
                _cacheUserInfoItem.gender = currntSelect == kSelectFirst ? GenderFemale:GenderMale;
            }else {
                _cacheUserInfoItem.handBallType = currntSelect == kSelectFirst ? HandDirectionTypeForeward:HandDirectionTypeBackward;
            }
            if (self.isWecomePersonVc) {
                [self firstLoginCheckData];
            }else {
                [self saveItemBtnEnable];
            }
        }
        [zhVc dismiss];
        [self.tabelView reloadData];
//        [self.tabelView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }];
}
#pragma mark - 设置身高和体重，训练时长
- (void)setHeightWithPersonmodel:(YFPersonModel *)model withIndexPath:(NSIndexPath *)indexPath {
    YFHeightPickerView *ftInchView = [YFHeightPickerView ftInchPickerView];
    
    if ([YFUserDefaults generalMetricSystemUnit]) {
        NSString *heightCm = [NSString stringWithFormat:@"%.0fcm",(_cacheUserInfoItem.height.floatValue * 100)];
        [ftInchView configuerFirstColValue:heightCm secondColValue:nil];
    }else {
        NSInteger ft = [_cacheUserInfoItem ftFormHeight];
        NSInteger inch = roundf([_cacheUserInfoItem inchFormHeight]);
        [ftInchView configuerFirstColValue:@(ft).stringValue secondColValue:@(inch).stringValue];
    }

    zhPopupController *zhVc = [YFAlertHelper zhpresentEaseInOutAlertView:ftInchView allowPan:NO dismissTouchMask:YES];
    [ftInchView setDidSelectHeight:^(NSString *ftStr, NSString *inchStr) {
        
        if ([YFUserDefaults generalMetricSystemUnit]) {
            model.subTitle = ftStr;
            _cacheUserInfoItem.height = @([ftStr trimingAllNumber].integerValue * 0.01).stringValue;
        }else {
            ftStr = [ftStr trimingAllNumber];
            inchStr = [inchStr trimingAllNumber];
            model.subTitle = [NSString stringWithFormat:@"%@'%@''",ftStr,inchStr];
            _cacheUserInfoItem.height = [UserInfoItem ft:ftStr.integerValue inch:inchStr.integerValue];
        }
        _setedHeight = YES;
        if (self.isWecomePersonVc) {
            [self firstLoginCheckData];
        }else {
            [self saveItemBtnEnable];
        }
        [zhVc dismiss];
        [self.tabelView reloadData];
//        [self.tabelView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }];
    
}


- (void)setWeightWithPersonmodel:(YFPersonModel *)model withIndexPath:(NSIndexPath *)indexPath {
    NSString *weightStr = @"";
    if ([YFUserDefaults generalMetricSystemUnit]) {
        // 使用公制单位
        weightStr = [NSString stringWithFormat:@"%0.fkg",round([_cacheUserInfoItem.weight floatValue])];
    }else {
        // 使用英制单位
        weightStr = [NSString stringWithFormat:@"%0.flbs",[Common kgToLbs:[_cacheUserInfoItem.weight floatValue]]];
    }
    YFWeightAlertPickerView *weightView = [YFWeightAlertPickerView weightAlertPickerViewWithWeight:weightStr];
    
    zhPopupController *zhVc = [YFAlertHelper zhpresentEaseInOutAlertView:weightView allowPan:NO dismissTouchMask:YES];
    [weightView setSelectCallback:^(NSString *callBackString) {
        model.subTitle = callBackString;
        callBackString = [callBackString trimingAllNumber];
        if ([YFUserDefaults generalMetricSystemUnit]) {
             _cacheUserInfoItem.weight = callBackString;
        }else {
             _cacheUserInfoItem.weight = @([Common lbsTokg:callBackString.floatValue]).stringValue;
        }
        _setedWeight = YES;
        if (self.isWecomePersonVc) {
            [self firstLoginCheckData];
        }else {
            [self saveItemBtnEnable];
        }
        [zhVc dismiss];
        [self.tabelView reloadData];
//        [self.tabelView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }];
}
- (void)setTraingWithPersonmodel:(YFPersonModel *)model withIndexPath:(NSIndexPath *)indexPath {
    YFTrainingAlertPickerView *trainView = [YFTrainingAlertPickerView trainingAlertPickerView];
    
  
    NSArray *trainStrArr = [self.cacheUserInfoItem.trainingTarget componentsSeparatedByString:@"-"];
    NSString *timeSection = @"";
    NSString *hours = @"";
    if (trainStrArr.count == 2) {
        hours = [NSString stringWithFormat:@"%@hour",trainStrArr.lastObject];
        timeSection = [SquashEnum stringWithTimeSectionType:[trainStrArr.firstObject integerValue]];
    }
    
    [trainView configuerFirstColValue:hours secondColValue:timeSection];
    zhPopupController *zhVc = [YFAlertHelper zhpresentEaseInOutAlertView:trainView allowPan:NO dismissTouchMask:YES];
    
    [trainView setDidSelectHeight:^(NSString *firstStr, NSString *secondStr) {
        _settedTraiing = YES;
        _cacheUserInfoItem.trainingTarget = [NSString stringWithFormat:@"%zd-%@",[SquashEnum timeSectionWithString:secondStr],[firstStr trimingAllNumber]];
        model.subTitle = [NSString stringWithFormat:@"%@ %@",firstStr,secondStr];
        if (self.isWecomePersonVc) {
            [self firstLoginCheckData];
        }else {
            [self saveItemBtnEnable];
        }
        [zhVc dismiss];
        [self.tabelView reloadData];
//        [self.tabelView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }];
}

#pragma mark - tabelView代理方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    YFPersonDataCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YFPersonDataCell" forIndexPath:indexPath];
    UserGroup *group = self.groups[indexPath.section];
    YFPersonModel *item = group.items[indexPath.row];
    [cell configerCellWithItem:item];
    if (indexPath.section == 0) {
        [cell configerCellWithItem:item];
        // 字符串修改
        [cell setTextChangeHandler:^(NSString *text) {
            item.subTitle = text;
        }];
        [cell setEndEdittextField:^(NSString *text) {
            if (indexPath.row == 0) {
                _cacheUserInfoItem.FirstName = text;
            }else if (indexPath.row == 1){
                _cacheUserInfoItem.lastName = text;
            }else if (indexPath.row == 2){
                _cacheUserInfoItem.birthYear = @([NSDate date].year - text.integerValue).stringValue;
            }else if (indexPath.row == 3){
                _cacheUserInfoItem.address = text;
            }else if (indexPath.row == 4){
                _cacheUserInfoItem.email = text;
            }
            if (self.isWecomePersonVc) {
                [self firstLoginCheckData];
            }else {
                [self saveItemBtnEnable];
            }
        }];
       
        [cell setBeginEditTextField:^(NSString *text) {
            // 若是被键盘挡住了，调整高度
//             [_tabelView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
        }];
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 70;
    }else {
        return 52;
    }
}
// 当拖拽时退出键盘
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}
#pragma mark - headView
- (UIView *)creatTabelviewHeaderView {
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, 141)];
    headView.backgroundColor = kSeparationLineColor;
    UIImageView *headImage = [[UIImageView alloc] initWithImage:kUserHeadPlaceholdImage];
    [headView addSubview:headImage];
    self.headImageView = headImage;
    
    UILabel *editLabel = [UILabel CreatLabelText:@"Edit" bgColor:nil textFont:kOpenSansFont(OpenSansRegular, 16) textColor:kTLightGray999 textAliment:NSTextAlignmentCenter];
    
    [headView addSubview:editLabel];
    
    [headImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headView.mas_top).offset(23);
        make.centerX.equalTo(headView.mas_centerX);
        make.width.height.mas_equalTo(75);
    }];
    [editLabel sizeToFit];
    [editLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(headView.mas_centerX);
        make.top.equalTo(headImage.mas_bottom).offset(13);
    }];
    
    [headImage clipsCornerRadius:75*0.5 borderWidth:0 borderColor:nil];
    self.headImageView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapGest = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapUploadHeadImage:)];
    [self.headImageView addGestureRecognizer:tapGest];
    
    return headView;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"icon"]) {
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:_cacheUserInfoItem.icon] placeholderImage:kUserHeadPlaceholdImage options:SDWebImageLowPriority|SDWebImageRetryFailed];
    }
}

- (void)dealloc {
    if (self.cacheUserInfoItem) {
        [self.cacheUserInfoItem removeObserver:self forKeyPath:@"icon"];
    }
}

- (void)tapUploadHeadImage:(UITapGestureRecognizer *)tapGes {
    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    [PhotoActionSheetViewController showInParentViewController:appdelegate.window.rootViewController alertType:UIAlertControllerStyleAlert animationType:DetailViewControllerPresentAnimationTypeUp actionBlock:^(kTapActionButtonType btnType) {
        if (btnType != kTapCacnelButton) {
            SystemSelectPhotoManager *photoManger = [SystemSelectPhotoManager selectPhotoManagerWithEditCaseType:kSystemDeflaut];
            self.photoManger = photoManger;
            [photoManger takePhotoBySource:btnType canEdit:YES parentViewController:self selectCallBlock:^(UIImage *selectImage, NSError *error) {
                // 获取照片
                [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                [YFLoginHelper uploadUserHeadIconImage:selectImage completed:^(NSString *url, NSError *error) {
                    [MBProgressHUD hideHUDForView:self.view animated:YES];
                    if (error == nil ) {
                        [MBProgressHUD showSuccessHudInView:self.view message:@"Upload image succeed" afterDelay:1.0];
                        _cacheUserInfoItem.icon = url;
                        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:kUserHeadPlaceholdImage options:SDWebImageLowPriority|SDWebImageRetryFailed];
                    }else {
                        [MBProgressHUD showTextHUDWithMessage:@"Upload image fail" inView:self.view];
                    }
                }];
            }];
        }
    }];
}

#pragma mark - footerView
- (UIView *)creatTableViewFooterView {
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kYFScreenWidth, kAutoHei(130))];
    footerView.backgroundColor = kSeparationLineColor;
 
    UIButton *nextButton = [UIButton creatButtonTitle:@"NEXT" bgColor:kYellowGreenColor textFont:kOpenSansFont(OpenSansExtraBold, 16) textColor:kTBlackText];
    [nextButton addTarget:self action:@selector(nextbuttonClick:) forControlEvents:UIControlEventTouchUpInside];
    [footerView addSubview:nextButton];
    self.nextButton = nextButton;
    self.nextButton.hidden = !self.isWecomePersonVc;
    [nextButton setTitleColor:kTLightGray999 forState:UIControlStateDisabled];
    self.nextButton.enabled = NO;
    [self changeNextButton];
    [nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(footerView);
        make.height.mas_equalTo(kAutoHei(50));
        make.width.mas_equalTo(kAutoWid(267));
        make.centerX.equalTo(footerView.mas_centerX).offset(10);
    }];
    
    return footerView;
}

- (void)changeNextButton {
    if (self.nextButton.enabled) {
        [self.nextButton clipsCornerRadius:3 borderWidth:0 borderColor:nil];
        self.nextButton.backgroundColor = kYellowGreenColor;
    }else {
        [self.nextButton clipsCornerRadius:3 borderWidth:1.5 borderColor:kTLightGray999];
        self.nextButton.backgroundColor = kSeparationLineColor;
    }
}

- (void)nextbuttonClick:(UIButton *)sender {
    if (self.nextButtonClick) {
        self.nextButtonClick();
    }
}

#pragma mark - 验证数据
- (BOOL)firstLoginCheckData {
    BOOL checkSuc = NO;
    if (_cacheUserInfoItem.lastName.length <= 0) {
        checkSuc = NO;
    }else if(_cacheUserInfoItem.FirstName.length <= 0){
        checkSuc = NO;
    }else if(_cacheUserInfoItem.getAge == 0){
        checkSuc = NO;
    }else if(_cacheUserInfoItem.address.length <= 0){
        checkSuc = NO;
    }
    else if (_settedTraiing == NO){
        checkSuc = NO;
    }else {
        checkSuc = YES;
    }
    //    else if(_setedHandType == NO){
    //        checkSuc = NO;
    //    }
//    else if(_setedHeight == NO){
//        //        checkSuc = NO;
//    }else if(_setedWeight == NO){
//        //        checkSuc = NO;
//    }
    self.nextButton.enabled = checkSuc;
    [self changeNextButton];
    return checkSuc;
}

//个人中心的保存按钮状态是否可点
- (BOOL)saveItemBtnEnable {
    BOOL checkSuc = NO;
    if (_cacheUserInfoItem.lastName.length <= 0 || _cacheUserInfoItem.FirstName.length <= 0 || _cacheUserInfoItem.getAge == 0) {
        checkSuc = NO;
    }else if (_cacheUserInfoItem.address.length <= 0 && self.oldUserInfoItem.address.length > 0){
        checkSuc = NO;
    }else if (_oldUserInfoItem.loginType == LoginTypeFacebook && _cacheUserInfoItem.email.length <= 0) {
        // faceBook登录的必须输入邮箱
        checkSuc = NO;
    }else {
        // 判断是否有改动用户信息
        if (![_oldUserInfoItem.lastName isEqualToString:_cacheUserInfoItem.lastName]) {
            checkSuc = YES;
        }else if (![_oldUserInfoItem.FirstName isEqualToString:_cacheUserInfoItem.FirstName]){
            checkSuc = YES;
        }else if (![_oldUserInfoItem.address isEqualToString:_cacheUserInfoItem.address]){
            checkSuc = YES;
        }else if (![_oldUserInfoItem.birthYear isEqualToString:_cacheUserInfoItem.birthYear]){
            checkSuc = YES;
        }else if (![_oldUserInfoItem.email isEqualToString:_cacheUserInfoItem.email]){
            checkSuc = YES;
        }else if (_oldUserInfoItem.gender != _cacheUserInfoItem.gender){
            checkSuc = YES;
        }else if (![_oldUserInfoItem.height isEqualToString:_cacheUserInfoItem.height]){
            checkSuc = YES;
        }else if (![_oldUserInfoItem.weight isEqualToString:_cacheUserInfoItem.weight]){
            checkSuc = YES;
        }else if (![_oldUserInfoItem.trainingTarget isEqualToString:_cacheUserInfoItem.trainingTarget]){
            checkSuc = YES;
        }else if (_oldUserInfoItem.handBallType != _cacheUserInfoItem.handBallType){
            checkSuc = YES;
        }
    }
    self.saveItem.enabled = checkSuc;
    return checkSuc;
}

@end
